package com.xique.blelock.view.Setting;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.ivin.crop.Log;
import com.xique.MyApplication;
import com.xique.blelock.NetUtils.NetResult;
import com.xique.blelock.NetUtils.XqNetClient;
import com.xique.blelock.R;
import com.xique.blelock.Utils.ACache;
import com.xique.blelock.Utils.Stringkey;
import com.xique.blelock.Utils.TimeUtil;
import com.xique.blelock.model.HistoryMessageInfo;
import com.xique.blelock.model.LockInfo;
import com.xique.blelock.model.MessageType;
import com.xique.blelock.model.UnreadMessage;
import com.xique.blelock.view.BaseActivity;
import com.xique.blelock.view.Home_Activity;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import me.leolin.shortcutbadger.ShortcutBadger;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


public class Message_Activity extends BaseActivity implements View.OnClickListener {
//    private LinearLayout BACK;
    private LinearLayout Mdevice,Mxitong,Mhuodong, Mbanben;




    @BindView(R.id.title)
    TextView title;

    @BindView(R.id.devicetip)
    TextView devicetip;
    @BindView(R.id.systemtip)
    TextView systemtip;
    @BindView(R.id.activitytip)
    TextView activitytip;

    private List<UnreadMessage> unreadMessageList;

    // 判断是不是点击通知跳转过来的
//    private boolean isJpushMessage = false;
    private  BroadcastReceiver mReceiver;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.message_activity);
        ButterKnife.bind(this);
        initview();



        IntentFilter filter = new IntentFilter();
        filter.addAction(Stringkey.Message_Event);
        mReceiver = new MessagePush();
        this.registerReceiver(mReceiver, filter);
    }

    @Override
    protected void onResume() {
        super.onResume();
        getUnreadMessage();
    }

    @Override
    protected void onDestroy() {
        unregisterReceiver(mReceiver);
        super.onDestroy();

    }

    private void getUnreadMessage() {
        //getUnreadMessageCount
        XqNetClient netClient =  new XqNetClient();
        JSONObject jsonobject = new JSONObject();

        try {
            jsonobject.put("token", userInfo.getToken());
            jsonobject.put("uid", userInfo.getUid());
            jsonobject.put("timestamp", TimeUtil.getSystemCurrentTimeLong()+"");

        } catch (JSONException e) {
            e.printStackTrace();
        }
        showProgressDialog();
        netClient.getUnreadMessageCount(jsonobject.toString()).enqueue(new Callback<NetResult<List<UnreadMessage>>>(){//获取验证码
            @Override
            public void onResponse(Call<NetResult<List<UnreadMessage>>> call, Response<NetResult<List<UnreadMessage>>> response) {
                Log.e("当前的返回的未读记录：："+JSON.toJSONString(response.body().getData()), "");
                if(response.body().isSuccess()){
                    unreadMessageList = response.body().getData();
                    Log.e("当前的返回的未读记录1111111111111：："+JSON.toJSONString(unreadMessageList), "");
                    if (unreadMessageList != null && (unreadMessageList.size() >0)) {
                        int badgeCount = 0;
                        for(UnreadMessage unreadMessage: unreadMessageList){
                            badgeCount += unreadMessage.getUnReadCount();

                            if(unreadMessage.getType() == MessageType.device){
                                if(unreadMessage.getUnReadCount()>0) {
                                    devicetip.setVisibility(View.VISIBLE);
                                    devicetip.setText(unreadMessage.getUnReadCount() + "");
                                }else{
                                    devicetip.setVisibility(View.GONE);
                                }
                            }else if(unreadMessage.getType() == MessageType.system){
                                if(unreadMessage.getUnReadCount()>0) {
                                    systemtip.setVisibility(View.VISIBLE);
                                    systemtip.setText(unreadMessage.getUnReadCount() + "");
                                }else{
                                    systemtip.setVisibility(View.GONE);
                                }
                            }else if(unreadMessage.getType() == MessageType.actitivity){
                                if(unreadMessage.getUnReadCount()>0) {
                                    activitytip.setVisibility(View.VISIBLE);
                                    activitytip.setText(unreadMessage.getUnReadCount()+"");
                                }else{
                                    activitytip.setVisibility(View.GONE);
                                }
                            }
                        }
                        if(badgeCount>0){
                            ACache.get(MyApplication.context).put(Stringkey.HasMessage, true);
                        }else{
                            ACache.get(MyApplication.context).put(Stringkey.HasMessage, false);
                        }
                        ShortcutBadger.applyCount(Message_Activity.this, badgeCount); //for 1.1.4+
                    }

                }else {
                    showToast(Message_Activity.this, "没有获取到设备列表 ");
                }
                hideProgressDialog();
            }

            @Override
            public void onFailure(Call<NetResult<List<UnreadMessage>>> call, Throwable t) {
                t.printStackTrace();
                hideProgressDialog();
            }
        });
    }

    private void initview() {
        Mdevice= findViewById(R.id.devices);
        Mxitong= findViewById(R.id.xitongggao);
        Mhuodong= findViewById(R.id.huodoingmessagh);
        Mbanben= findViewById(R.id.banmen);
        Mdevice.setOnClickListener(this);
        Mxitong.setOnClickListener(this);
        Mhuodong.setOnClickListener(this);
        Mbanben.setOnClickListener(this);
//        BACK.setOnClickListener(this);

        title.setText("信息通知");
    }

    @OnClick(R.id.BACKER)
    public void BackLastPage(){
        finish();
    }

    @Override
    public void onClick(View v) {
         if (v==Mxitong) {//系统公告
            Intent serverIntent = new Intent(this,SystemNotifiActiviy.class); // 跳界面
            startActivity(serverIntent);
        } else if (v == Mdevice) {//设备信息\
            Intent intent = new Intent(this,devicemessages.class); // 跳界面
            startActivity(intent);

        }else if (v == Mhuodong) {//活动消息
            Intent serverIntent = new Intent(this,HuodongActiviy.class); // 跳界面
            startActivity(serverIntent);
        }else if (v == Mbanben) {//版本跟新
            Toast.makeText(this,"无新版本",Toast.LENGTH_SHORT).show();
        }


    }


    public class MessagePush extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            HistoryMessageInfo historyMessageInfo = (HistoryMessageInfo) intent.getSerializableExtra(Stringkey.JpushKey);
            Log.e("MessageActivity广播收到的信息：", "");
            //把改消息添加列表里面去
            getUnreadMessage();
        }
    }
}
